﻿using Common;
using Common.Cache;
using Microsoft.Extensions.DependencyInjection;
using MongoDB;
using MongoDB.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Quartz.Service
{
    public class QuartzJob : IJob
    {
        // 注入DI provider
        private readonly IMongoDB _mongoDB;
        private readonly IApiService _apiService;
        private readonly ITaskTipService _sendEmail;
        private readonly ICache _cache;
        public QuartzJob(IServiceProvider provider)
        {
            using (var scope = provider.CreateScope())
            {
                _mongoDB = scope.ServiceProvider.GetService<IMongoDB>();
                _apiService = scope.ServiceProvider.GetService<IApiService>();
                _sendEmail = scope.ServiceProvider.GetService<ITaskTipService>();
                _cache = scope.ServiceProvider.GetService<ICache>();
            }
        }
        
        /// <summary>
        /// 执行定时任务
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            var DataMap = context.JobDetail.JobDataMap;
            //获取任务参数
            var guid = DataMap.GetString("guid");
            var TaskManage = await _mongoDB.GetCollection<Mongo_TaskManageModel>("Task_Manage").FindInfoAsync(m => m.guid == guid);
            try
            {
                //只有开启的任务才能执行
                if (TaskManage!=null&&TaskManage.IsOpen == 1)
                {
                    //开始调用接口，并记录执行时间
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    var Response = await _apiService.ExecuteTask(TaskManage);
                    stopwatch.Stop();
                    decimal second = ((decimal)stopwatch.ElapsedMilliseconds / (decimal)1000);
                    //写入执行记录
                    await _mongoDB.GetCollection<Mongo_TaskRecordModel>("Task_Record").InsertOneAsync(new Mongo_TaskRecordModel
                    {
                        TaskName = TaskManage.TaskName,
                        CreateTime = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc),
                        Second = second,
                        GroupName = TaskManage.GroupName,
                        ResponseBody = Response,
                        Method= TaskManage.Method,
                        Url= TaskManage.TaskUrl,
                        RequestBody= TaskManage.RequestBody
                    });
                    if (TaskManage.IsTip == 1)
                    {
                        _cache.Remove($"ErrorCache_{TaskManage.guid}");
                    }
                }
            }
            catch (Exception ex)
            {
                //写入错误日志记录
                await _mongoDB.GetCollection<Mongo_TaskErrorModel>("Task_Error").InsertOneAsync(new Mongo_TaskErrorModel
                {
                    TaskName = TaskManage.TaskName,
                    CreateTime = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc),
                    GroupName = TaskManage.GroupName,
                    Message=ex.Message,
                    TaskUrl= TaskManage.TaskUrl,
                    Method= TaskManage.Method,
                    RequestBody= TaskManage.RequestBody
                });
                if (TaskManage.IsTip == 1)
                {
                    _sendEmail.SendErrorTipEmail(TaskManage, ex);
                }
            }
        }
    }
}
